<template>
  <div class="row-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ area }}区 {{ row }}排</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="$router.push(`/cabinets/${area}`)"
        >
          返回区域
        </el-button>
      </div>

      <div class="cabinet-grid">
        <div
          v-for="cabinet in cabinets"
          :key="cabinet.id"
          class="cabinet-item"
          :class="cabinet.status"
          @click="handleCabinetClick(cabinet)"
        >
          <span class="cabinet-number">{{ cabinet.number }}</span>
          <span class="cabinet-status">
            {{ getStatusText(cabinet.status) }}
          </span>
        </div>
      </div>

      <!-- 渲染子路由组件 (Detail.vue) -->
      <router-view :key="$route.fullPath" />

    </el-card>

    <!-- 柜子操作对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <div v-if="selectedCabinet">
        <p>柜子编号：{{ selectedCabinet.id }}</p>
        <p>状态：{{ getStatusText(selectedCabinet.status) }}</p>
        <template v-if="selectedCabinet.status === 'available'">
          <el-button type="primary" @click="handleUseCabinet">使用柜子</el-button>
        </template>
        <template v-else-if="selectedCabinet.status === 'in_use'">
          <p>开始时间：{{ formatDate(selectedCabinet.startTime) }}</p>
          <p>使用密码：{{ selectedCabinet.password }}</p>
          <el-button 
            type="danger" 
            @click="handleReleaseCabinet"
            v-if="selectedCabinet.userId === user.id"
          >释放柜子</el-button>
          <p v-else class="text-warning">只有使用者才能释放柜子</p>
        </template>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

export default {
  name: "RowCabinets",
  data() {
    return {
      dialogVisible: false,
      selectedCabinet: null
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user
    }),
    ...mapGetters(["getCabinetsByRow"]),
    area() {
      return this.$route.params.area;
    },
    row() {
      return this.$route.params.row;
    },
    cabinets() {
      // 确保 area 和 row 参数存在且有效再获取柜子列表
      if (this.area && this.row) {
         return this.getCabinetsByRow(this.area, this.row);
      }
      return [];
    },
    isAdmin() {
      return this.user && this.user.role === "admin";
    },
    dialogTitle() {
      return this.selectedCabinet ? `柜子 ${this.selectedCabinet.id} 详情` : "柜子详情";
    }
  },
  watch: {
    // 监听路由变化，确保 area 和 row 参数有效
    '$route.params': {
      immediate: true,
      handler(newParams) {
        if (!newParams.area || !newParams.row || !this.getCabinetsByRow(newParams.area, newParams.row)) {
           // 如果 area 或 row 参数无效，导航回 /cabinets
           this.$router.replace('/cabinets').catch(()=>{});
        }
      }
    }
  },
  mounted() {
    console.log('Row.vue mounted');
    console.log('Area:', this.area);
    console.log('Row:', this.row);
    console.log('Cabinets:', this.cabinets);
  },
  methods: {
    getStatusText(status) {
      const statusMap = {
        available: "空闲",
        in_use: "使用中"
      };
      return statusMap[status] || status;
    },
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },
    handleCabinetClick(cabinet) {
      // 导航到 Detail 级别的路由
      const targetPath = `/cabinets/${this.area}/${this.row}/${cabinet.id}`;
      if (this.$route.fullPath !== targetPath) {
        this.$router.push(targetPath).catch(() => {}); // 添加错误处理并避免重复导航
      }
    },
    async handleUseCabinet() {
      try {
        const { password } = await this.$store.dispatch("useCabinet", {
          cabinetId: this.selectedCabinet.id,
          userId: this.user.id
        });
        this.$message.success(`使用成功！取件密码：${password}`);
        this.dialogVisible = false;
      } catch (error) {
        this.$message.error(error.message || "使用失败");
      }
    },
    async handleReleaseCabinet() {
      try {
        await this.$store.dispatch("releaseCabinet", this.selectedCabinet.id);
        this.$message.success("释放成功");
        this.dialogVisible = false;
      } catch (error) {
        this.$message.error(error.message || "释放失败");
      }
    }
  }
};
</script>

<style scoped>
.row-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.cabinet-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  padding: 20px;
  justify-content: center;
  justify-items: center;
}

.cabinet-item {
  aspect-ratio: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.cabinet-item:hover {
  transform: scale(1.05);
}

.cabinet-item.available {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.cabinet-item.in_use {
  background-color: #f4f4f5;
  border-color: #909399;
}

.cabinet-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.cabinet-status {
  font-size: 14px;
  color: #909399;
}
</style>
